<template>
	<!-- 忘记密码 -->
	<view class="forget-password">
		<nav-bar :title="i18n.login.forgetPassword" @_back="_back" />
		<view class="forget-container">
			<custom-input icon="user" special v-model="info.username" :placehold="i18n.login.enterUser" @specialFun="specialFun" />
			<custom-input icon="code" v-if="smsSwitc" :phoneName="info.username" :loginType="loginType" v-model="info.code" isVerification :placehold="i18n.login.enterCode" />
			<custom-input icon="password" v-model="info.password" isPwd :placehold="i18n.login.enterNewPassword" />
			<custom-input icon="password" v-model="info.repassword" isPwd :placehold="i18n.login.enterPasswordAgain" />
			<custom-submit class="forget-submit" :loading="loading" :title="i18n.common.submit" @click="submit" />
		</view>
	</view>
</template>

<script>
	import NavBar from '@/components/NavBar/index.vue'
	import CustomInput from '@/components/CustomInput/index.vue'
	import CustomSubmit from '@/components/CustomSubmit/index.vue'
	import {
		Toast
	} from '@/utils/util.js'
	import {
		forgetPassword,
		check_mobile,
		check_email
	} from '@/api/index.js'
	import {mapGetters} from 'vuex'
	export default {
		components: {
			NavBar,
			CustomInput,
			CustomSubmit
		},
		computed: {
			...mapGetters(['smsSwitc']),
			i18n() {
				return this.$t('message');
			}
		},
		data() {
			return {
				info: {},
				loading: false,
				loginType: 0
			}
		},
		methods: {
			async submit() {
				if (!this.info.username) return Toast(this.i18n.login.enterUser);
				if (!this.info.code && this.smsSwitc) return Toast(this.i18n.login.enterCode);
				if (!this.info.password) return Toast(this.i18n.login.enterNewPassword);
				if (!this.info.repassword) return Toast(this.i18n.login.enterPasswordAgain);
				this.loading = true;
				
				let check = !this.smsSwitc? true: !this.loginType? await this.checkEmailCode(): await this.checkMobileCode();
				if (!check) return this.loading = check;
				let {
					error,
					res
				} = await forgetPassword(this.info);
				if (error) return this.loading = false;;
				await Toast(this.i18n.login.modifySuccess);
				this.loading = false;
				this._back()
			},
			_back() {
				uni.navigateTo({
					url: '/pages/login/index'
				})
			},
			// 短信验证码验证
			async checkMobileCode() {
				let {error,res} = await check_mobile({mobile_code: this.info.code});
				if (error) return false;
				return true;
			},
			// 邮箱验证码验证
			async checkEmailCode() {
				let {error,res} = await check_email({email_code: this.info.code});
				if (error) return false;
				return true;
			},
			// 判断哪种类型
			specialFun(val) {
				this.loginType = val;
			}
		}
	}
</script>

<style lang="scss">
	.forget-password {
		color: rgba(255, 255, 255, .4);

		.forget-container {
			width: 630rpx;
			margin: 90rpx auto 0;

			.forget-submit {
				margin-top: 100rpx;
			}
		}
	}
</style>
